# -*- coding: utf-8 -*-

import time
import json
import copy
import datetime

from flask_wtf import Form
from wtforms import (
    StringField, IntegerField, FloatField, BooleanField, DateTimeField,
    SelectField, DateField,
    ValidationError)
from wtforms import widgets
from wtforms.fields.html5 import URLField, EmailField
from wtforms.validators import DataRequired, Email, Length, NumberRange, Regexp

from app.models import UserPlan, Destination
from app.utils import api_error, trim, safe_int, safe_float


class PlanBookForm(Form):
    data = StringField(label='预定线路数据')
    plan_id = IntegerField(label='计划id')
    poi_id_type = IntegerField(label='poi id类型')
    device_id = StringField(label='设备id')
    city_names = StringField(label='城市')
    name = StringField(label='计划名')
    create_date = IntegerField(label='创建日期')
    cover = URLField(label='封面url')

    def validate_data(self, field):
        try:
            data = json.loads(field.data)
        except:
            return api_error(49999)
        self.data.data = data

    def validate_plan_id(self, field):
        plan = UserPlan.objects.filter(id=field.data).first()
        self.plan.data = plan

    def validate_create_date(self, field):
        date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(field.data))
        self.date.data = date


def check_start_count(request, default_count=20):
    start = 0
    if 'start' in request.args:
        try:
            start = int(trim(request.args['start']))
        except ValueError:
            return api_error(1)
        if start < 0:
            return api_error(1)

    count = default_count
    if 'count' in request.args:
        try:
            count = int(trim(request.args['count']))
        except ValueError:
            return api_error(1)
        if count <= 0:
            return api_error(1)
    return start, count


class VacationPoiSearchForm(Form):
    keyword = StringField(label='关键字', max_length=50)
    destination_id = IntegerField(label='目的地id')
    category = IntegerField(label='poi类型')
    lat = FloatField(label='lat')
    lng = FloatField(label='lng')

    def clean_destination_id(self):
        destination_id = safe_int(self.cleaned_data.get('destination_id', 0))
        destination = Destination.objects.filter(id=destination_id).first()
        if not destination:
            raise api_error(49999)
        return destination


class SupportConsultationForm(Form):
    name = StringField(
        label=u"用户名",
        validators=[
            DataRequired(message=u'请填写用户名'),
            Length(0, 50, message=u'用户名长度必须在 0-50 之间'),
        ])
    tel = StringField(
        label=u"手机号码",
        validators=[
            DataRequired(message=u"请填写手机号码"),
            Length(6, 20, message=u'手机号码长度必须在 6-20 之间')
        ])


class FeedbackForm(Form):
    content = StringField(
        label=u"反馈内容",
        validators=[
            DataRequired(message=u'请填写反馈内容')
        ])
    email = StringField(
        label=u"邮件",
        validators=[
            DataRequired(message=u"请填写邮件"),
            Email(message=u"邮件格式不正确")
        ])


class LocalityInfoForm(Form):
    name = StringField(
        label=u"中文名称",
        validators=[
            DataRequired(message=u"请填写国家中文名称"),
            Length(0, 50, message=u"国家中文名称长度必须在 0-50 之间")
        ]
    )
    name_en = StringField(
        label=u"英文名称",
        validators=[
            DataRequired(message=u"请填写国家英文名称"),
            Length(0, 50, message=u"国家中文名称长度必须在 0-50 之间")
        ]
    )
    time_zone = IntegerField(
        label=u"时区",
        description=u"正数为东区，负数为西区",
        validators=[
            DataRequired(message=u"请填写国家时区"),
        ]
    )
    cover = URLField(
        label=u"封面",
        validators=[
            DataRequired(message=u"请上传国家封面图片"),
        ]
    )
    longitude = FloatField(
        label=u'经度',
        validators=[
            DataRequired(message=u"请填写国家经度"),
        ]
    )
    latitude = FloatField(
        label=u"纬度",
        validators=[
            DataRequired(message=u"请填写国家纬度"),
        ]
    )
    itinerary_covers = StringField(
        label=u"行程封面",
        description=u"用回车区别多个图片",
        validators=[
            DataRequired(message=u"请上传国家行程图片"),
        ]
    )


class DestinationInfoForm(Form):
    name = StringField(
        label=u"目的地名称",
        validators=[
            DataRequired(message=u"请填写目的地名称"),
        ]
    )
    longitude = FloatField(
        label=u'经度',
        validators=[
            DataRequired(message=u"请填写目的地经度"),
        ]
    )
    latitude = FloatField(
        label=u"纬度",
        validators=[
            DataRequired(message=u"请填写目的地纬度"),
        ]
    )
    tags = StringField(label=u"标签", description=u"多个标签用回车区分")
    max_days = IntegerField(
        label=u"推荐天数(最大值)",
        validators=[
            DataRequired(message=u"请填写推荐天数(最大值)"),
        ]
    )
    min_days = IntegerField(
        label=u"推荐天数(最小值)",
        validators=[
            DataRequired(message=u"请填写推荐天数(最小值)"),
        ]
    )
    periphery = StringField(label=u"周边")
    images = StringField(
        label=u"图片",
        validators=[
            DataRequired(message=u"请上传目的地图片"),
        ]
    )


class ProductOrderForm(Form):
    def __init__(self, *args, **kwargs):

        dynamic_fields = copy.deepcopy(kwargs['fields'])
        custom_option = copy.deepcopy(kwargs['custom_option'])
        del kwargs['fields']
        del kwargs['custom_option']
        super(ProductOrderForm, self).__init__(*args, **kwargs)

        """
        if dynamic_fields.get('en_name'):
            self.fields['first_name'] = forms.CharField(label='护照英文姓', max_length=40,
                    widget=widgets.TextInput(attrs={'placeholder': '姓(拼音)'}),
                    error_messages={'required':u'护照英文姓 必须填写'})
            self.fields['last_name'] = forms.CharField(label='护照英文名', max_length=40,
                    widget=widgets.TextInput(attrs={'placeholder': '名(拼音)'}),
                    error_messages={'required':u'护照英文名 必须填写'})
        """
        if dynamic_fields.get('first_name'):
            first_name = StringField(label='护照英文姓',
                                     max_length=40,
                                     widget=widgets.TextInput(
                                         u'姓(拼音)'),
                                     error_messages={
                                         'required': u'护照英文姓 必须填写'})
        if dynamic_fields.get('last_name'):
            last_name = StringField(label='护照英文名',
                                    max_length=40,
                                    widget=widgets.TextInput(
                                        u'名(拼音)'),
                                    error_messages={
                                        'required': u'护照英文名 必须填写'})

        if dynamic_fields.get('baby_count'):
            baby_count = IntegerField(label='是否婴儿/婴儿数量',
                                      error_messages={
                                          'required': u'是否带婴儿 必须填写'})

        if dynamic_fields.get('sex'):
            sex_CHOICES = (
                (0, "男"),
                (1, "女"),
            )
            sex = SelectField(label='性别',
                              choices=sex_CHOICES,
                              # widget=forms.Select,
                              error_messages={
                                  'required': u'性别 必须填写'})

        if dynamic_fields.get('contact_name'):
            contact_name = StringField(label='姓名',
                                       max_length=40,
                                       widget=widgets.TextInput(
                                           u'中文姓名'),
                                       error_messages={
                                           'required': u'中文姓名 必须填写'})

        if dynamic_fields.get('contact_tel'):
            contact_tel = StringField(label='手机',
                                      max_length=40,
                                      widget=widgets.TextInput(
                                          u'手机'),
                                      error_messages={
                                          'required': u'联系人手机 必须填写'})

        if dynamic_fields.get('contact_email'):
            contact_email = EmailField(label='邮箱',
                                       widget=widgets.TextInput(
                                           u'邮箱'),
                                       error_messages={
                                           'required': u'联系人邮箱 必须填写'})

        if dynamic_fields.get('weixin'):
            weixin = StringField(label='微信号', max_length=40,
                                 widget=widgets.TextInput(u''),
                                 error_messages={
                                     'required': u'微信号 必须填写'})

        if dynamic_fields.get('shipping_address'):
            shipping_address = StringField(label='收货地址',
                                           max_length=255,
                                           widget=widgets.TextInput(
                                               u''),
                                           error_messages={
                                               'required': u'收货地址 必须填写'})

        if dynamic_fields.get('date'):
            date = DateTimeField(label='使用日期',
                                 widget=widgets.TextInput(u''),
                                 error_messages={
                                     'required': u'使用日期 必须填写'})

            if dynamic_fields.get('use_days'):
                use_days = StringField(label='使用天数',
                                       max_length=60,
                                       widget=widgets.TextInput(
                                           ''),
                                       error_messages={
                                           'required': u'使用天数 必须填写'})

            if dynamic_fields.get('arrive_time'):
                arrive_time = DateTimeField(label='到达时间',
                                            widget=widgets.TextInput(
                                                ''),
                                            error_messages={
                                                'required': u'到达时间 必须填写'})

            if dynamic_fields.get('delivery_location'):
                delivery_location = StringField(label='送达地点',
                                                max_length=255,
                                                widget=widgets.TextInput(
                                                    ''),
                                                error_messages={
                                                    'required': u'送达地点 必须填写'})

            if dynamic_fields.get('flight'):
                flight = StringField(label='航班号', max_length=10,
                                     widget=widgets.TextInput(
                                         u'航班号'),
                                     error_messages={
                                         'required': u'航班号 必须填写'})

            if dynamic_fields.get('user_waiting_time'):
                user_waiting_time = DateTimeField(label='候车时间',
                                                  widget=widgets.TextInput(
                                                      ''),
                                                  error_messages={
                                                      'required': u'候车时间 必须填写'})

            if dynamic_fields.get('get_on_address'):
                get_on_address = StringField(label='上车地点',
                                             max_length=255,
                                             widget=widgets.TextInput(
                                                 ''),
                                             error_messages={
                                                 'required': u'上车地点 必须填写'})

            if dynamic_fields.get('take_off_time'):
                take_off_time = DateTimeField(label='起飞时间',
                                              widget=widgets.TextInput(
                                                  ''),
                                              error_messages={
                                                  'required': u'起飞时间 必须填写'})

            if dynamic_fields.get('hotel_name'):
                hotel_name = StringField(label='酒店',
                                         widget=widgets.TextInput(
                                             ''),
                                         error_messages={
                                             'required': u'酒店 必须填写'})

            if dynamic_fields.get('hotel_address'):
                hotel_address = StringField(label='酒店地址',
                                            widget=widgets.TextInput(
                                                ''),
                                            error_messages={
                                                'required': u'酒店地址 必须填写'})

            if dynamic_fields.get('ticket_counter'):
                ticket_counter = StringField(label='取票柜台',
                                             widget=widgets.TextInput(
                                                 ''),
                                             error_messages={
                                                 'required': u'取票柜台 必须填写'})

            for option in custom_option:
                self.fields[option['name_en']] = StringField(
                    label=option['name'],
                    max_length=60,
                    widget=widgets.TextInput(''),
                    error_messages={'required': u'%s 必须填写' % (option['name'])})
            detail = BooleanField(error_messages={'required': u'必须同意协议'})

